<?php


namespace App\Admin\Controllers;


use App\Admin\Actions\Good\DownLoad;
use App\Admin\Actions\Good\Import;
use App\Admin\Actions\Good\ImportAsin;
use App\Admin\Services\GoodService;
use App\Http\Controllers\Controller;
use App\Model\ExportGoodJob;
use App\Model\Good;
use App\Model\ImportJob;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodController extends Controller
{
    /**
     * 商品首页
     *
     * @param Content $content
     * @param GoodService $goodService
     * @return Content
     *
     * @author: 梅杰 2020/2/18 21:48
     */
    public function index(Content $content, GoodService $goodService)
    {

        // 获取库存总金额
        $total = Good::query()->select([DB::raw("SUM(price * stock) as total")])->first()->total ?? 0;
        Admin::css('css/jquery.dataTables.min.css');
        $content->view('Good.index', ['amount' => $total, 'is_admin' => Admin::user()->inRoles(['susan', 'administrator'])]);
        Admin::js(('js/datatable-responsive/datatables.responsive.min.js'));
        Admin::js('js/datatables/jquery.dataTables.min.js');
        Admin::disablePjax();

        return $content;
    }


    /**
     * @desc 获取datatables 格式的商品列表
     *
     * @param Request $request
     * @param GoodService $goodService
     *
     * @return JsonResponse
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-17 13:53:02
     */
    public function getGoodList(Request $request, GoodService $goodService)
    {

        $data = $goodService->getGoodsList($request->input('columns'),
            $request->input('order'),
            $request->input('length', 10),
            $request->input('start', 0)
        );

        return datatableResponse($request->input('draw'), $data['total'], $data['data']);
    }


    /**
     * @desc 设置商品价格
     *
     * @param Request $request
     *
     * @return JsonResponse
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-17 14:05:30
     */
    public function setPrice(Request $request)
    {
        if (!is_numeric($request->input('price'))) {
            return response()->json([
                'code' => 100,
                'msg' => '请输入正确得价格'
            ]);
        }
        Good::query()->where('id', (int)$request->input('id', 0))
            ->update(['price' => $request->input('price')]);

        return response()->json([
            'code' => 200,
            'msg' => 'success'
        ]);
    }

    /**
     * @desc 设置商品价格
     *
     * @param Request $request
     * @param GoodService $goodService
     *
     * @return JsonResponse
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-17 14:05:30
     */
    public function setRemark(Request $request, GoodService $goodService)
    {
        if ($goodService->setRemark($request->input('id'), $request->input('content'))) {
            return response()->json([
                'code' => 200,
                'msg' => 'success'
            ]);
        }

        return response()->json([
            'code' => 500,
            'msg' => 'system error'
        ]);
    }


    /**
     * @desc 删除商品
     *
     * @param Request $request
     * @return JsonResponse
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-17 15:42:37
     */
    public function delete(Request $request)
    {
        if (Good::query()->where('id', $request->input('id'))->delete()) {
            return response()->json([
                'code' => 200,
                'msg' => 'success'
            ]);
        }
        return response()->json([
            'code' => 500,
            'msg' => 'system error'
        ]);
    }


    /**
     * @desc 出库或者入库
     *
     * @param Request $request
     * @return JsonResponse
     *
     * @author: 梅杰[meijie3169@dingtalk.com] at 2020-03-17 15:42:37
     */
    public function stock(Request $request, GoodService $goodService)
    {
        if (!is_numeric($request->input('stock'))) {
            return response()->json([
                'code' => 100,
                'msg' => '请输入正确操作数量'
            ]);
        }
        if ($request->input('stock') < 0 || (int)$request->input('stock') - $request->input('stock') != 0) {
            return response()->json([
                'code' => 100,
                'msg' => '操作数量为正整数'
            ]);
        }

        if ($goodService->updateStock(
            $request->input('id'),
            $request->input('stock'),
            $request->input('type'))
        ) {
            return response()->json([
                'code' => 200,
                'msg' => 'success'
            ]);
        }
        return response()->json([
            'code' => 500,
            'msg' => 'system error'
        ]);
    }


    /**
     * 导入Asin
     *
     * @param Content $content
     * @return Content
     *
     * @author: 梅杰 2020/2/18 21:47
     */
    public function ImportAsin(Content $content)
    {
        $grid = new Grid(new ImportJob());
        // 根据权限筛选不同的导出记录
        $grid->model()->where('type', 0)
            ->orderBy('id', 'desc');
        $grid->column('id', '序号')->sortable();
        $grid->column('operator.name', '操作人')->sortable();

        $grid->column('total', '导入总记录数')->sortable();
        $grid->column('has_handle_count', '已处理数')->sortable();
        $grid->column('success_count', '导入成功数')->sortable();

        $grid->column('status', '当前状态')->sortable()->display(function ($status) {
            switch ($status) {
                case 1:
                    $title = "导入中";
                    break;
                case 2:
                    $title = "处理成功";
                    break;
                default :
                    $title = "待导入";
                    break;
            }
            return $title;
        });


        $grid->column('created_at', '导入时间')->sortable();
        $grid->column('updated_at', '更新时间')->sortable();


        $grid->column('title', '查看错误')->modal(function ($model) {
            $data = $model->failed()->get(['id', 'row', 'type', 'error_value']);
            $error = [];
            foreach ($data as $datum) {
                switch ($datum->type) {
                    case 0:
                        $message = "asin 无效：" . $datum->error_value;
                        break;
                    case 1:
                        $message = "sku无效" . $datum->error_value;
                        break;
                    case 2:
                        $message = "操作失败";
                        break;
                    case 3:
                        $message = "未查找到相关供货商信息：" . $datum->error_value;
                        break;
                    default:
                        $message = "系统错误";
                }
                $error[] = [
                    $datum->row,
                    $message
                ];
            }
            return new Table(['行号', '错误信息'], $error);
        });

        $grid->disableCreateButton();
        $grid->disableExport();
        $grid->disableFilter();
        $grid->actions(function ($actions) {
            // 去掉编辑
            $actions->disableEdit();

            // 去掉查看
            $actions->disableView();
        });

        $grid->disableBatchActions();

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportAsin());
        });
        $grid->paginate(10);

        return $content->row($grid);
    }


    /**
     * 通过asin 导出商品
     *
     * @param Content $content
     * @param Request $request
     * @return Content|void
     *
     * @author: 梅杰 2020/2/19 21:44
     */
    public function exportGood(Content $content, Request $request)
    {
        $grid = new Grid(new ExportGoodJob());
        // 根据权限筛选不同的导出记录
        $grid->model()->where('type', 0)
            ->orderBy('id', 'desc');

        if (!Admin::user()->inRoles(['susan', 'administrator'])) {
            $grid->model()->where('user_id', Admin::user()->id);
        }

        $grid->column('id', '序号')->sortable();

        $grid->column('user_id', '操作者')->display(function ($userId) {
            return Administrator::query()
                    ->where('id', $userId)
                    ->first(['username'])
                    ->username ?? '暂无相关信息';
        });

        $grid->column('created_at', '导入时间');

        $grid->column('is_over', '当前状态')->display(function ($isOver) {

            switch ($isOver) {
                case 0:
                    $msg = "正在导出中";
                    break;
                case 1:
                    $msg = "导出成功";
                    break;
                case 2:
                default:
                    $msg = "导出失败";
            }
            return $msg;
        });


        $grid->disableCreateButton();
        $grid->disableExport();

        $grid->actions(function ($actions) {
            // 去掉编辑
            $actions->disableEdit();
            // 去掉查看
            $actions->disableView();

            if ($actions->row->is_over == 1) {
                $actions->add(new DownLoad());
            }

        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new Import());
        });
        $grid->paginate(10);
        return $content->row($grid);

    }


    /**
     * 更新amazon图
     *
     * @return RedirectResponse
     */
    public function syncMws()
    {
        GoodService::syncMws();
        admin_toastr("正在更新中", "success", ['timeOut' => 5000]);
        return back();
    }

}
